<?php

namespace app\modules\agent\controllers;

use app\models\Agent;
use app\models\AgentConfig;
use app\models\AgentLog;
use app\models\AgentPackage;
use app\models\Card;
use app\models\KeyMap;
use app\models\Package;
use app\models\User;
use app\models\UserConfig;
use app\models\UserPackage;
use app\models\Util;
use Yii;
use yii\data\Pagination;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;

/**
 * 用户管理
 * Class UserController
 * @package app\modules\agent\controllers
 */
class UserController extends BaseController
{
    /**
     * 代理商列表
     * @return string
     * @throws ForbiddenHttpException
     */
    public function actionAgentList()
    {
        if (AgentConfig::getConfig($this->agent->id, 'multi_agent') != 1) {
            throw new ForbiddenHttpException('没有权限。');
        }

        $query = Agent::find();
        $query->andWhere(['pid' => $this->agent->id]);
        $query->andWhere(['status' => Agent::STATUS_OK]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('id DESC');
        $query->offset($pagination->offset)->limit($query->limit);
        $agentList = $query->all();
        return $this->render('agent_list', [
            'agentList' => $agentList,
            'pagination' => $pagination,
        ]);
    }

    /**
     * 添加修改代理商
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     * @throws \yii\base\Exception
     */
    public function actionAgentEdit()
    {
        if (AgentConfig::getConfig($this->agent->id, 'multi_agent') != 1) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        $agent_id = $this->agent->id;
        if (!empty($id)) {
            $agent = Agent::findOne(['id' => $id]);
            if (empty($agent) || !Agent::checkRelation($this->agent->id, $agent->id)) {
                throw new NotFoundHttpException('没有找到代理商信息。');
            }
        } else {
            $agent = new Agent();
            $agent->pid = $this->agent->id;
            $agent->status = Agent::STATUS_OK;
            $agent->create_time = time();
        }
        if ($agent->load($this->post())) {
            if (!empty($agent->password) && !preg_match('/^\$2y/', $agent->password)) {
                $agent->password = Yii::$app->security->generatePasswordHash($agent->password);
            }
            if(empty($agent->password)){
                $agent->password = $password;
            }
            if ($agent->save()) {
                AgentLog::info($this->agent->id, '保存代理商', print_r($agent->attributes, true));
                Yii::$app->session->addFlash('success', '数据已保存。');
                Yii::$app->session->setFlash('redirect', json_encode([
                    'url' => Url::to(['/agent/user/agent-list']),
                    'txt' => '代理商列表'
                ]));
				
                if(!$id){
					$comm_type = AgentConfig::getConfig($this->agent->id, 'comm_agent');
                    $agentid = $agent->attributes['id'];
					if ($comm_type == 1) {
						AgentConfig::setConfig($agentid, 'comm_agent', '2');
					} else {
						AgentConfig::setConfig($agentid, 'comm_agent', '0');
					}
                   /** $package = Package::find()->where(['exception'=>1])->all();
                    foreach ($package as $key => $value) {
                        $agent_package = new AgentPackage();
                        $agent_package->agent_id = $agentid;
                        $agent_package->package_id = $package[$key]['id'];
                        $agent_package->cost_price = $package[$key]['price'];
                        $agent_package->sale_price = $package[$key]['price'];
                        $agent_package->name = $package[$key]['name'];
                        $agent_package->xuzhi = $package[$key]['xuzhi'];
                        $agent_package->isp = $package[$key]['isp'];
                        $agent_package->save();
                    }  */
                }
                
            }
        }
        return $this->render('agent_edit', [
            'agent' => $agent,
            'agent_id' => $agent_id,
        ]);
    }

    /**
     * 代理商详情
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionAgentView()
    {
        if (AgentConfig::getConfig($this->agent->id, 'multi_agent') != 1) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        $agent = Agent::findOne(['id' => $id]);
        if (empty($agent) || !Agent::checkRelation($this->agent->id, $agent->id)) {
            throw new NotFoundHttpException('没有找到代理商信息。');
        }
        return $this->render('agent_view', [
            'agent' => $agent,
        ]);
    }

    /**
     * 重置代理商密码AJAX接口
     * @return array
     * @throws \yii\base\Exception
     */
    public function actionResetAgentPassword()
    {
        if (AgentConfig::getConfig($this->agent->id, 'multi_agent') != 1) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        $agent = Agent::findOne(['id' => $id]);
        if (empty($agent) || !Agent::checkRelation($this->agent->id, $agent->id)) {
            return ['error' => 'SERVER', 'message' => '没有找到代理商。'];
        }
        $password = Util::randomStr(6, 1);
        $agent->password = Yii::$app->security->generatePasswordHash($password);
        $agent->save(false);
        return ['new_password' => $password];
    }

    /**
     * 代理商设置
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionAgentConfig()
    {
        if (AgentConfig::getConfig($this->agent->id, 'multi_agent') != 1) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $id = $this->get('id');
        $agent = Agent::findOne(['id' => $id]);
        if (empty($agent) || !Agent::checkRelation($this->agent->id, $agent->id)) {
            throw new NotFoundHttpException('没有找到代理商。');
        }
        return $this->render('agent_config', [
            'agent' => $agent,
        ]);
    }

    /**
     * 保存代理商配置AJAX接口
     * @return array
     */
    public function actionSaveAgentConfig()
    {
        if (AgentConfig::getConfig($this->agent->id, 'multi_agent') != 1) {
            return ['error' => 'SERVER', 'message' => '没有权限。'];
        }
        $agentId = $this->get('agent_id');
        $k = $this->get('k');
        $v = $this->get('v');
        $agent = Agent::findOne(['id' => $agentId]);
        if (empty($agent) || !Agent::checkRelation($this->agent->id, $agent->id)) {
            return ['error' => 'SERVER', 'message' => '没有找到代理商。'];
        }
        if (empty($k)) {
            return ['error' => 'SERVER', 'message' => '参数错误，没有找到键。'];
        }
        $r = AgentConfig::setConfig($agent->id, $k, $v);
        if (!$r) {
            return ['error' => 'SERVER', 'message' => '无法保存代理商配置。'];
        }
        return [];
    }

    /**
     * 代理商套餐设置
     * @return string
     * @throws ForbiddenHttpException
     * @throws NotFoundHttpException
     */
    public function actionAgentPackage()
    {
        if (AgentConfig::getConfig($this->agent->id, 'multi_agent') != 1) {
            throw new ForbiddenHttpException('没有权限。');
        }
        $agent = Agent::findOne(['id' => $this->get('agent_id')]);
        if (empty($agent) || !Agent::checkRelation($this->agent->id, $agent->id)) {
            throw new NotFoundHttpException('没有找到代理商。');
        }
        $agentPackageList = [];
        /** @var AgentPackage $parentAgentPackage */
        foreach (AgentPackage::find()->andWhere(['agent_id' => $agent->pid])->each() as $parentAgentPackage) {
            $agentPackageList[] = $parentAgentPackage;
        }
        $agentPackageMap = [];
        /** @var AgentPackage $agentPackage */
        foreach (AgentPackage::find()->andWhere(['agent_id' => $agent->id])->each() as $agentPackage) {
            $agentPackageMap[$agentPackage->package_id] = $agentPackage;
        }
        return $this->render('agent_package', [
            'agent' => $agent,
            'agentPackageList' => $agentPackageList,
            'agentPackageMap' => $agentPackageMap,
        ]);
    }

    /**
     * 保存代理商价格AJAX接口
     * @return array
     */
    public function actionSaveAgentPackage()
    {
        if (AgentConfig::getConfig($this->agent->id, 'multi_agent') != 1) {
            return ['error' => 'SERVER', 'message' => '没有权限。'];
        }
        $agentId = $this->get('agent_id');
        $packageId = $this->get('package_id');
        $usePool = $this->get('use_pool');
        $costPrice = $this->get('cost_price');
		$salePrice = $this->get('sale_price');

        $agent = Agent::findOne(['id' => $agentId]);
        if (empty($agent) || !Agent::checkRelation($this->agent->id, $agent->id)) {
            return ['error' => 'SERVER', 'message' => '没有找到代理商。'];
        }
        $package = Package::findOne(['id' => $packageId]);
        if (empty($package)) {
            return ['error' => 'SERVER', 'message' => '没有找到套餐。'];
        }
        $selfAgentPackage = AgentPackage::findOne(['agent_id' => $this->agent->id, 'package_id' => $package->id]);
        if (empty($selfAgentPackage)) {
            return ['error' => 'SERVER', 'message' => '没有找到套餐。'];
        }
        if (empty($costPrice) || $costPrice < $selfAgentPackage->cost_price) {
            return ['error' => 'SERVER', 'message' => '价格错误。'];
        }
		if (empty($salePrice) || $salePrice < $costPrice) {
            return ['error' => 'SERVER', 'message' => '零售价格错误。'];
        }
        $agentPackage = AgentPackage::findOne(['agent_id' => $agent->id, 'package_id' => $package->id]);
        if (empty($agentPackage)) {
            $agentPackage = new AgentPackage();
            $agentPackage->agent_id = $agent->id;
            $agentPackage->package_id = $package->id;
			$agentPackage->isp = $package->isp;
			$agentPackage->xuzhi = $package->xuzhi;
			$agentPackage->name = $selfAgentPackage->name;
        }
        $agentPackage->cost_price = $costPrice;
        $agentPackage->sale_price = $salePrice;
        if ($selfAgentPackage->use_pool == 1) {
            $agentPackage->use_pool = $usePool;
        }
        $agentPackage->save();
        return [];
    }
    //删除下级代理商套餐
    public function actionDeleteAgentPackage(){
        $id = $this->get('id');
        $agent_id = $this->get('agent_id');
        $agentPackage = AgentPackage::findOne(['package_id' => $id,'agent_id' => $agent_id]);
        $model = AgentPackage::findOne(['id'=>$agentPackage['id']]);
        if (empty($model)) {
            return ['error' => 'SERVER','message' => '没有找到该代理套餐'];
        }try{
            $model->delete();
            return [];
        }catch (\Throwable $e){
        }
        
    }
    /**
     * 用户列表
     * @return string
     */
    public function actionUserList()
    {
        $query = User::find();
        $query->andWhere(['agent_id' => $this->agent->id]);
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $query->orderBy('id DESC');
        $query->offset($pagination->offset)->limit($pagination->limit);
        $userList = $query->all();
        return $this->render('user_list', [
            'userList' => $userList,
            'pagination' => $pagination,
        ]);
    }

    /**
     * 添加修改用户
     * @return string
     * @throws NotFoundHttpException
     * @throws \yii\base\Exception
     */
    public function actionUserEdit()
    {
        $id = $this->get('id');
        if (!empty($id)) {
            $user = User::findOne(['id' => $id, 'agent_id' => $this->agent->id]);
            if (empty($user)) {
                throw new NotFoundHttpException('没有找到用户信息。');
            }
        } else {
            $user = new User();
            $user->agent_id = $this->agent->id;
            $user->status = User::STATUS_OK;
            $user->create_time = time();
        }
        if ($user->load($this->post())) {
            if (!empty($user->password) && !preg_match('/^\$2y/', $user->password)) {
                $user->password = Yii::$app->security->generatePasswordHash($user->password);
            }
            if ($user->save()) {
                AgentLog::info($this->agent->id, '保存用户', print_r($user->attributes, true));
                Yii::$app->session->addFlash('success', '数据已保存。');
                Yii::$app->session->setFlash('redirect', json_encode([
                    'url' => Url::to(['/agent/user/user-list']),
                    'txt' => '用户列表'
                ]));
            }
        }
        return $this->render('user_edit', [
            'user' => $user,
        ]);
    }

    /**
     * 用户详情
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionUserView()
    {
        $id = $this->get('id');
        $user = User::findOne(['id' => $id, 'agent_id' => $this->agent->id]);
        if (empty($user)) {
            throw new NotFoundHttpException('没有找到用户信息。');
        }
        return $this->render('user_view', [
            'user' => $user,
        ]);
    }

    /**
     * 重置用户密码AJAX接口
     * @return array
     * @throws \yii\base\Exception
     */
    public function actionResetUserPassword()
    {
        $id = $this->get('id');
        $user = User::findOne(['id' => $id, 'agent_id' => $this->agent->id]);
        if (empty($user)) {
            return ['error' => 'SERVER', 'message' => '没有找到用户。'];
        }
        $password = Util::randomStr(6, 1);
        $user->password = Yii::$app->security->generatePasswordHash($password);
        $user->save(false);
        return ['new_password' => $password];
    }

    /**
     * 用户设置
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionUserConfig()
    {
        $id = $this->get('id');
        $user = User::findOne(['id' => $id, 'agent_id' => $this->agent->id]);
        if (empty($user)) {
            throw new NotFoundHttpException('没有找到用户。');
        }
        return $this->render('user_config', [
            'user' => $user,
        ]);
    }

    /**
     * 保存用户配置AJAX接口
     * @return array
     */
    public function actionSaveUserConfig()
    {
        $uid = $this->get('uid');
        $k = $this->get('k');
        $v = $this->get('v');
        $user = User::findOne(['id' => $uid, 'agent_id' => $this->agent->id]);
        if (empty($user)) {
            return ['error' => 'SERVER', 'message' => '没有找到用户。'];
        }
        if (empty($k)) {
            return ['error' => 'SERVER', 'message' => '参数错误，没有找到键。'];
        }
        $r = UserConfig::setConfig($user->id, $k, $v);
        if (!$r) {
            return ['error' => 'SERVER', 'message' => '无法保存用户配置。'];
        }
        return [];
    }

    /**
     * 用户套餐设置
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionUserPackage()
    {
        $user = User::findOne(['id' => $this->get('id'), 'agent_id' => $this->agent->id]);
        if (empty($user)) {
            throw new NotFoundHttpException('没有找到用户。');
        }
        $agentPackageList = [];
        /** @var AgentPackage $agentPackage */
        foreach (AgentPackage::find()->andWhere(['agent_id' => $this->agent->id])->each() as $agentPackage) {
            $agentPackageList[] = $agentPackage;
        }
        $userPackageMap = [];
        /** @var UserPackage $userPackage */
        foreach (UserPackage::find()->andWhere(['uid' => $user->id])->each() as $userPackage) {
            $userPackageMap[$userPackage->package_id] = $userPackage;
        }
        return $this->render('user_package', [
            'user' => $user,
            'agentPackageList' => $agentPackageList,
            'userPackageMap' => $userPackageMap,
        ]);
    }

    /**
     * 保存用户价格AJAX接口
     * @return array
     */
    public function actionSaveUserPackage()
    {
        $uid = $this->get('uid');
        $packageId = $this->get('package_id');
        $usePool = $this->get('use_pool');
        $costPrice = $this->get('cost_price');

        $user = User::findOne(['id' => $uid, 'agent_id' => $this->agent->id]);
        if (empty($user)) {
            return ['error' => 'SERVER', 'message' => '没有找到用户。'];
        }
        $package = Package::findOne(['id' => $packageId]);
        if (empty($package)) {
            return ['error' => 'SERVER', 'message' => '没有找到套餐。'];
        }
        $selfAgentPackage = AgentPackage::findOne(['agent_id' => $this->agent->id, 'package_id' => $package->id]);
        if (empty($selfAgentPackage)) {
            return ['error' => 'SERVER', 'message' => '没有找到套餐。'];
        }
        if (empty($costPrice) || $costPrice < $selfAgentPackage->cost_price) {
            return ['error' => 'SERVER', 'message' => '价格错误。'];
        }
        $userPackage = UserPackage::findOne(['uid' => $user->id, 'package_id' => $package->id]);
        if (empty($userPackage)) {
            $userPackage = new UserPackage();
            $userPackage->uid = $user->id;
            $userPackage->package_id = $package->id;
        }
        if ($selfAgentPackage->use_pool == 1) {
            $userPackage->use_pool = $usePool;
        }
        $userPackage->cost_price = $costPrice;
        $userPackage->save();
        return [];
    }

    /**
     * 用户分析统计
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionUserAnalyze()
    {
        $id = $this->get('id');
        $user = User::findOne(['id' => $id, 'agent_id' => $this->agent->id]);
        if (empty($user)) {
            throw new NotFoundHttpException('没有找到用户信息。');
        }
        // 总数量
        $amount = Card::find()->andWhere(['uid' => $user->id])->count();
        // 状态统计
        $statusCount = Card::find()
            ->asArray()
            ->select([
                'status' => 'status',
                'amount' => new Expression('COUNT(0)'),
            ])
            ->andWhere(['uid' => $user->id])
            ->groupBy('status')
            ->all();
        array_walk($statusCount, function (&$item) {
            $item['status'] = KeyMap::getValue('card_status', $item['status']);
        });
        $statusCount = ArrayHelper::map($statusCount, 'status', 'amount');
        return $this->render('user_analyze', [
            'user' => $user,
            'amount' => $amount,
            'statusCount' => $statusCount,
        ]);
    }
    
    /**
     * 代理商日志
     */
    public function actionAgentLog()
    {
        $query = AgentLog::find()->andFilterWhere(['agent_id'=>$this->agent->id]);
        $query->andFilterWhere(['like', 'info', $this->get('search_content')]);
        $search_start_date = $this->get('search_start_date');
        if (!empty($search_start_date)) {
            $query->andFilterWhere(['>=', 'time', strtotime($search_start_date)]);
        }
        $search_end_date = $this->get('search_end_date');
        if (!empty($search_end_date)) {
            $query->andFilterWhere(['<', 'time', strtotime($search_end_date) + 86400]);
        }
        $pagination = new Pagination(['totalCount' => $query->count()]);
        $model_list = $query->orderBy('time DESC')->offset($pagination->offset)->limit($pagination->limit)->all();
        return $this->render('log', [
            'model_list' => $model_list,
            'pagination' => $pagination
        ]);
    }
    /**
     * 获取日志详情AJAX接口
     * @return array
     */
    public function actionLogDetail()
    {
        $id = $this->get('id');
        $log = AgentLog::findOne(['id' => $id]);
        if (empty($log)) {
            return ['error' => 'SERVER', 'message' => '没有找到日志信息。'];
        }
        return [
            'result' => 'success',
            'log' => [
                'id' => $log->id,
                'info' => $log->info,
                'data' => $log->data,
            ],
        ];
    }
}
